// stores/counter.js
import { defineStore } from 'pinia';
import auth from "@/utils/auth.js";
import apis from "@/apis/index.js";
import utils from "@/utils/utils";
import config from "@/config/index.js";
import atlas from "@/utils/atlas.js";//地图相关方法
import uniFunc from "@/utils/uni.js";//二封装uni的方法

const useCounterStore = defineStore('counter', {
  state: () => ({
    ycMpParams: {
      basicInfo: {},
      userInfo: {},
      showMobile: 0,
      token: "",
      curriculumInfo: {},
      courseList: []
    },
    orderDetails: {},//订单详情
    tab2Params: [],//tab2参数
  }),

  getters: {
    navBarHeight: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //console.log("[systemInfo]", systemInfo)
      //获取状态栏信息-h5没有状态栏
      let statusBarHeight = systemInfo.statusBarHeight;
      let navBarHeight = 0
      //获取胶囊信息:uni.getMenuButtonBoundingClientRect-->App | H5 | 支付宝小程序不支持
      // #ifndef H5 || APP-PLUS || MP-ALIPAY
      const menuButtonBoundingInfo = uni.getMenuButtonBoundingClientRect();
      console.log("[胶囊信息]", menuButtonBoundingInfo)
      // (胶囊底部高度-状态栏的高度)+(胶囊顶部高度-状态栏的高度)*2=导航栏的高度
      navBarHeight = (menuButtonBoundingInfo.top - systemInfo.statusBarHeight) * 2 + (menuButtonBoundingInfo.bottom - systemInfo.statusBarHeight);
      // #endif
      return Number(statusBarHeight) + Number(navBarHeight)
    },
    windowWidth: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //屏幕的宽度
      return systemInfo.windowWidth;
    },
    windowHeight: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //屏幕的高度
      return systemInfo.windowHeight;
    },
    //是否登录
    isLogin: (state) => {
      let result = true
      let { token, userInfo } = state.ycMpParams
      if (!token) result = false
      if (!userInfo) result = false
      if (userInfo && !userInfo.mobile) result = false
      return result
    },
    //系统信息
    systemInfoSync: (state) => {
      return uni.getSystemInfoSync()
    },
  },

  actions: {
    priceRange(lessonContent) {
      if (!lessonContent) return
      let arr = <any>[]
      lessonContent.forEach(element => {
        if (element.discountPrice) arr.push(Number(element.discountPrice))
      });
      arr.sort((a, b) => a - b);
      if (arr.length) return arr[0]
      return 0
    },

    logout() {
      this.setYcParams("token", "");
      this.setYcParams("userInfo", {});
    },

    //更新手机号
    async getPhoneNumber(code) {
      if (!code) return
      if (!this.ycMpParams.token) await this.toLogin()
      let token = await apis.authUserMobile({ code })
      this.setYcParams("token", token)
      await this.getUserInfo()
    },

    async toLogin() {
      if (this.ycMpParams.token) return
      // #ifdef MP-WEIXIN 
      let jscode = await auth.login()
      let resp = await apis.mapWeiXinGetToken({ jscode })
      this.setYcParams("token", resp)
      await this.getUserInfo()
      // #endif

      // #ifdef H5
      let codeH5 = this.getUrlCode('code')
      if (codeH5 && !this.ycMpParams["token"]) {
        let resp = await apis.wxLogin({ code: codeH5, type: 'H5' })
        if (resp.token) this.setYcParams("token", resp.token)
        await this.getUserInfo()
        return resp.showMobile
      } else {
        this.getWeChatCode()
      }
      // #endif
    },

    //获取H5微信登录返回的code
    getWeChatCode() {
      const appID = config.appIdH5;  //公众号appID
      const callBack = window.location.href; //回调地址 就是你的完整地址登录页

      //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
      window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        appID + '&redirect_uri=' + encodeURIComponent(callBack) +
        `&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
    },

    // 正则匹配请求地址中的参数函数
    getUrlCode(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    },

    //用户信息
    async getUserInfo() {
      let resp = await apis.getUserInfo({ type: "details" })
      if (resp == null) return this.logout()
      if (!resp.nickname) resp.nickname = resp._id.slice(-4)
      this.setYcParams("userInfo", resp)
      console.log("用户信息", resp)
    },

    async init() {
      let ycMpParams = uni.getStorageSync("ycMpParams");
      this.ycMpParams = utils.deepcopy(ycMpParams);
      // #ifdef H5
      if (window.location.hostname == 'localhost') {
        this.ycMpParams.token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI2NzYzZWE0NWNmY2M5NDc2NDMxMDI4NzQiLCJleHAiOjE3NTQzNjQzNjIsImlhdCI6MTc0NjU4ODM2Mn0.QXqJE8phUggJX-6yw4UlF0f1mApK8Pm6U9ScqANF3kA"
        await this.setYcParams("token", this.ycMpParams.token)
      }
      // #endif

      // #ifdef MP-WEIXIN
      if (!this.ycMpParams.token) await this.toLogin()
      // #endif
      if (this.ycMpParams.token) await this.getUserInfo()
      let basicInfo = await apis.webHome({
        type: "details",
      });
      await this.setYcParams("basicInfo", basicInfo)
    },

    setYcParams(type, value) {
      let ycMpParams = uni.getStorageSync("ycMpParams");
      if (!ycMpParams) ycMpParams = {}
      ycMpParams[type] = value;
      uni.setStorageSync("ycMpParams", ycMpParams);
      this.ycMpParams = utils.deepcopy(ycMpParams);
    },

    //APP手机号一键登录
    async appPhoneNumberLogin() {
      let resp = await uni.appPhoneNumberLogin()
      console.log("APP手机号一键登录", resp)
    },
    //APP微信登录
    async uploadAvatar(e) {
      let resp = await this.uploadLafFile(e)
      await apis.operationtUserInfo({ headUrl: resp })
      this.getUserData()
    },
    async uploadNickname(e) {
      await apis.operationtUserInfo({ nickname: e })
      this.getUserData()
    },
    //获取七牛信息
    async getQIniuInfo() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'https://app.taozapp.cn/api/uploadFile/uploadPhoto',
          method: "POST",
        }).then(data => {
          resolve(data.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //上传文件
    async uploadFile(element) {
      let qiNiuInfo = await this.getQIniuInfo()
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "https://upload-z2.qiniup.com",
          filePath: element,
          formData: { token: qiNiuInfo.token },
          name: 'file',
          success: ({ data }) => {
            let imgRes = JSON.parse(data)
            let path = qiNiuInfo.cdnUrl + imgRes.key
            resolve(path)
          },
          fail: (e) => {
            uni.$uv.toast(e)
          }
        })
      })
    },

    //上传laf文件
    async uploadLafFile(filePath) {
      let header = {
        "content-type": "application/json",
        "Authorization": `Bearer ${this.ycMpParams.token}`
      }
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${config.baseUrl}/system_utils/upload_file`,
          filePath,
          formData: {},
          name: 'file',
          header,
          success: ({ data }) => {
            console.log("上传laf文件", data)
            let info = JSON.parse(data)
            resolve(info.data)
          },
          fail: (e) => {
            console.log("上传laf文件失败", e)
            utils.showToast(e)
          }
        })
      })
    },


    //获取定位
    async getCurrentLocation() {
      let cwydLocation = uni.getStorageSync('cwydLocation')
      if (cwydLocation) {
        this.location = cwydLocation
      } else {
        let resp = await auth.getLocation()
        let cityInfo = await atlas.getCityInfo(resp.longitude, resp.latitude)
        resp.city = cityInfo.addressComponent
        uni.setStorageSync('cwydLocation', resp);
        this.location = resp
      }
    },
    setNavCss() {
      uni.setNavigationBarColor({
        frontColor: "#ffffff", //文字颜色
        backgroundColor: "#53A2F9", //底部背景色
      });
    },
    //去魔学院
    async goMoxueyuan() {
      return await apis.getUserInfo({
        data: { type: "h5" },
        type: "moxueyuanLoginUrl"
      })
    },
  },
});

export default useCounterStore
